// small example using images and x11
package main

import "fmt"
import "io/ioutil"
import "os"
import "image"
import "image/draw"

import "code.google.com/p/x-go-binding/xgb"
import "code.google.com/p/freetype-go/freetype"

func PutString(text string) *image.RGBA {	
	context := freetype.NewContext()
	fontfile := "/usr/share/fonts/liberation/LiberationMono-Regular.ttf"
	fontBytes, err := ioutil.ReadFile(fontfile)
	if err != nil { fmt.Println(err); return nil }
	font, err := freetype.ParseFont(fontBytes)
	if err != nil { fmt.Println(err); return nil }	
	rgba := image.NewRGBA(image.Rect(0, 0, 600, 400))    
	draw.Draw(rgba, rgba.Bounds(), image.White, image.ZP, draw.Src)
//	
	context.SetDst(rgba)
	context.SetFont(font)
	context.SetFontSize(12)
	context.SetClip(rgba.Bounds())
	context.SetDPI(72)
	context.SetSrc(image.Black)
//
	start := freetype.Pt(10, 10) 
	_, err = context.DrawString(text, start)
	return rgba
}

const DEPTH = 24

func openX() (con *xgb.Conn, win xgb.Id, gc xgb.Id) {	
	con, err := xgb.Dial(os.Getenv("DISPLAY"))
	if err != nil { return }
	win = con.NewId()
    s := con.DefaultScreen()
    gc = con.NewId()
    fmt.Printf( "win, gc = %x, %x\n", win, gc )
	con.CreateWindow(DEPTH, win, s.Root, 150, 150, 200, 200, /* bw */ 0, /* class */0, /* visual */ 0, 0, nil)
	con.ChangeWindowAttributes(win, xgb.CWBackPixel|xgb.CWEventMask,
        []uint32{
            s.WhitePixel,
            xgb.EventMaskExposure | xgb.EventMaskKeyRelease,
        })
    con.CreateGC(gc, win, xgb.GCBackground | xgb.GCForeground, []uint32{s.BlackPixel, s.WhitePixel})    
    con.MapWindow(win)
    return con, win, gc
}

func main() {
	rgba := PutString("Hello") // , World!")
	fmt.Println("rect:", rgba.Rect)
//
	con, win, gc := openX()
//
	var (width = uint16(rgba.Rect.Dx()); height = uint16(rgba.Rect.Dy()); depth = uint8(DEPTH))
	// fmt.Printf("rgba: width, height = %v, %v\n", width, height)
	const (x = 10; y = 10; pad = 0)
	const (bytesPerPixel = 4) // (depth + 7) / 8)
	var (size = int(width) * int(height) * bytesPerPixel; off = 0)
	fmt.Printf("bytes per pixel for depth %v: %v; size = %v, size' = %v\n", depth, bytesPerPixel, size, size+off)
	bytes := make([]byte, size+off)
	bindex := 0
	for _, p := range rgba.Pix {
		bytes[bindex] = p; bindex += 1
	}
	fmt.Println("bindex:", bindex)
    for { 
		con.PutImage(xgb.ImageFormatZPixmap, win, gc, width, height, x, y, pad, depth, bytes)
    	_, err := con.WaitForEvent()
    	if err != nil { return } 
    	
    }	
}


